<template>
	<div>
		<el-form :model="formData" label-width="120px" :rules="rules" ref="payrollformaddRef">
<!-- 			<el-row>
				<el-col :span="6">
					<el-form-item label="年度开账">
						<el-radio-group v-model="formData.settlement" @input="radioEvent">
							<el-radio :label="true">是</el-radio>
							<el-radio :label="false">否</el-radio>
						</el-radio-group> 
					</el-form-item>
				</el-col>				
				<el-col :span="6"  v-show="formData.settlement">
					<el-form-item label="数据年份">
						<el-date-picker type="year" v-model="formData.settlementNumber" value-format="yyyy" @change="SettlementNumberEvent"></el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row v-if="CheckSettlementResult.StatusCode==500 && CheckSettlementResult.Message!=''">
				<el-col :span="24">
					<el-form-item label="提示:">
						<p style="color: #E6A23C;margin: 0px 0px;">{{ CheckSettlementResult.Message }}</p> 
					</el-form-item>
				</el-col>
			</el-row> -->
			<el-form-item label="项目名称">
				<el-input v-model="project.ProjectName" disabled></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="6">
					<el-form-item label="施工类别" prop="constructionType">
						<el-select v-model="formData.constructionType" style="width: 100%;">
							<el-option v-for="(item,index) in $parent.$parent.constructionType" :value="item.Value"
								:label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<!-- 				<el-col :span="6">
					<el-form-item label="施工部位" prop="constructionPart">
						<el-select v-model="formData.constructionPart" style="width: 100%;">
							<el-option v-for="(item,index) in $parent.$parent.constructionPart" :value="item.Value"
								:label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="工作内容" prop="jobContent">
						<el-select v-model="formData.jobContent" style="width: 100%;">
							<el-option v-for="(item,index) in $parent.$parent.payrollFormConstructionType"
								:value="item.Value" :label="item.Description"></el-option>
						</el-select>
					</el-form-item>
				</el-col> -->
				<el-col :span="6">
					<el-form-item label="责任人" prop="personId">
						<el-select v-model="formData.personId" style="width: 100%;">
							<el-option v-for="(item,index) in $store.state.AllUsers" :value="item.Id"
								:label="item.UserName" v-if="item.RoleId != '1'"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="开始时间" prop="createTime">
						<el-date-picker style="width: 100%;"
						      v-model="formData.createTime"
						      type="month" value-format="yyyy-MM-ddTHH:mm:ss.000Z"
						      placeholder="请选择开始时间">
						    </el-date-picker>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="6">
					<el-form-item label="单号" prop="payrollNumber">
						<el-input v-model="formData.payrollNumber"></el-input>
					</el-form-item>
				</el-col> -->
				<el-col :span="6">
					<el-form-item label="方量(平方数量)" prop="squarequantity">
						<el-input  type="number" v-model="formData.squarequantity" @blur="gettotalPrice"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="6">
					<el-form-item label="单价" prop="price">
						<el-input type="number" v-model="formData.price" @blur="gettotalPrice"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="总价" prop="totalprice">
						<el-input disabled v-model="formData.totalprice"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="明细总计">
						<el-input disabled v-model="detailTotalprice" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 			<el-row>
				<el-col :span="3">
					<el-form-item label="资料文件上传">
						<UploadFileF ref="AnotherData" :multiple="true" :another-data="AnotherData"
							:showfilelist="true" :upshow="false" content="上传文件" btnsize="medium"></UploadFileF>
					</el-form-item>
				</el-col>
			</el-row> -->

			<el-row>
				<el-col :span="24">
					<el-form-item label="施工部位" prop="constructionPart">
						<el-input v-model="formData.constructionPart" type="textarea"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="工作内容" prop="jobContent">
						<el-input v-model="formData.jobContent" type="textarea"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24">
					<el-popover placement="right" width="430" trigger="click">
						<el-table :data="projectUserList" @select="selectionLineChangeHandle" style="max-height: 600px;overflow: auto;"
							@select-all="selectionLineChangeHandle" ref="projectUserListRef">
							<el-table-column type="selection" width="42" align="center"></el-table-column>
							<el-table-column width="100" property="UserName" label="姓名"
								align="center"></el-table-column>
							<el-table-column header-align="center" prop="UserNumber" label="工号"
								align="center"></el-table-column>
							<el-table-column header-align="center" prop="Phone" label="联系电话" align="center"
								width="150"></el-table-column>
						</el-table>
						<el-button type="primary" icon="el-icon-plus" slot="reference" size="mini">添加人员</el-button>
					</el-popover>
					<el-table :data="formData.users" style="width: 100%;" ref="multipleTable" class="tablelabel"
						:cell-style="{ padding: '5px 0 ' }">
						<el-table-column header-align="center" fixed prop="id" label="姓名" align="center">
							<template slot-scope="scope">
								{{ getUserInfo(scope.row,'UserName') }}
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="UserNumber" label="工号" align="center">
							<template slot-scope="scope">
								{{ getUserInfo(scope.row,'UserNumber') }}
							</template>
						</el-table-column>
						<!-- 						<el-table-column header-align="center" prop="jobCreateTime" label="工作开始时间" align="center">
							<template slot-scope="scope">
								 <el-date-picker v-if="scope.row.isupdata" @blur="TimeChange(scope.row)"
								      v-model="scope.row.jobCreateTime"  format="yyyy - MM - dd"
								      type="date"
								      placeholder="选择日期">
								    </el-date-picker>
								<p v-else>{{ timeForMat(scope.row.jobCreateTime) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="jobCreateTime" label="工作结束时间" align="center">
							<template slot-scope="scope">
								 <el-date-picker v-if="scope.row.isupdata" @blur="TimeChange(scope.row)"
								      v-model="scope.row.jobEndTime" format="yyyy - MM - dd"
								      type="date"
								      placeholder="选择日期">
								    </el-date-picker>
								<p v-else>{{ timeForMat(scope.row.jobEndTime) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="jobContent" label="工作内容" align="center">
							<template slot-scope="scope">
								<el-input v-model="scope.row.jobContent" v-if="scope.row.isupdata"></el-input>
								<p v-else>{{ scope.row.jobContent }}</p>
							</template>
						</el-table-column> -->
						<el-table-column header-align="center" prop="workingDays" label="工天" align="center">
							<template slot-scope="scope">
								<el-input v-model="scope.row.workingDays" v-if="scope.row.isupdata"></el-input>
								<p v-else>{{ scope.row.workingDays }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="price" label="单价" align="center">
							<template slot-scope="scope">
								<el-input v-model="scope.row.price" v-if="scope.row.isupdata"></el-input>
								<p v-else>{{ scope.row.price }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="price" label="金额" align="center">
							<template slot-scope="scope">
								<p>{{ (scope.row.price * scope.row.workingDays).toFixed(2) }}</p>
							</template>
						</el-table-column>
						<el-table-column header-align="center" prop="UserNumber" align="center" label="操作">
							<template slot-scope="scope">
								<!-- <el-button type="text" plain size="mini" @click="tableHandler(scope.row,'updata')">{{ scope.row.isupdata?'完成':'编辑' }}</el-button> -->
								<el-button type="text" plain size="mini" style="color: #F56C6C;"
									@click="tableHandler(scope.row,'delete')">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24" align="right">
					<el-button type="primary" @click="addPayrollFormHandler()" v-loading="btn_loading">保存</el-button>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>

<script>
	import dayjs from 'dayjs'
	import UploadFileF from "../../UploadFileF";
	import {
		CheckAmount
	} from "../../../../public/Scriput/Public.js"

	export default {
		name: 'payrollFormAdd',
		components: {
			UploadFileF
		},
		props: {
			project: {
				type: Object,
				required: false
			},
			closeFun: {
				type: Function,
				reuqired: false,
			},
			jobContentList: {
				type: Array,
				required: false
			}
		},
		data() {
			var squarequantityRule = (rule, value, callback) => {
				if (value == '') callback(new Error('请输入方量(平方数量)'))
				else if (!CheckAmount(value)) callback(new Error('请填写有效的方量数额(保留两位小数)'))
				else callback()
			};
			var priceRule = (rule, value, callback) => {
				if (value == '') callback(new Error('请输入方量单价'))
				else if (!CheckAmount(value)) callback(new Error('请填写有效的方量单价(保留两位小数)'))
				else callback()
			};
			return {
				formData: {
					settlementNumber: '',
					settlement:false,
					projectId: 0,
					payrollFormType: 1,
					payrollNumber: "",
					constructionType: '',
					constructionPart: '',
					jobContent: '',
					squarequantity: 0,
					price: 0,
					personId: '',
					totalprice: 0,
					remarks: "",
					createTime: dayjs(Date()).format('YYYY-MM-DDTHH:mm:ss.000Z'),
					users: []
				},
				projectUserList: [],
				selectEdUserList: [],
				AnotherData: {
					//项目模块
					FileType: 256,
					//项目Id号
					id: 0,
					//Type：1：收方工资单 2、应发工资单、3报销单 
					Type: 1,
					Single: false,
				},
				rules: {
					constructionType: [{
						trigger: 'change',
						message: '请选择施工类别',
						required: true
					}],
					// constructionPart:[ { trigger:'change',message:'请选择施工部位',required:true } ],
					// jobContent:[ { trigger:'change',message:'请选择工作内容',required:true } ],
					personId: [{
						trigger: 'change',
						message: '请选择责任人',
						required: true
					}],
					squarequantity: [{
						trigger: 'blur',
						validator: squarequantityRule
					}],
					price: [{
						trigger: 'blur',
						validator: priceRule
					}],
					createTime: [{
						trigger: 'change',
						message: '请选择开始时间',
						required: true
					}],
					payrollNumber: [{
						trigger: 'blur',
						message: '请输入单号',
						required: true
					}],
				},					
				CheckSettlementResult:{
					Status: false,
					Message:'',
				},
				//数据提交中
				btn_loading:false,
			}
		},
		computed: {
			gettotalPrice() {
				const {
					squarequantity,
					price
				} = this.formData || 0
				let result = squarequantity * price
				if (isNaN(result)) {
					this.formData.totalprice = 0
				} else {
					this.formData.totalprice = result.toFixed(2)
				}
			},
			detailTotalprice() {
				let money_result = 0
				this.formData.users.map(x => {
					const {
						price,
						workingDays
					} = x || 0
					money_result += (price * workingDays)
				})
				return money_result.toFixed(2)
			}
		},
		created() {
			this.formData.projectId = this.project.Id
			this.getPorjectUsers()
		},
		mounted() {

		},
		methods: {
			addPayrollFormHandler() {
				let _this = this
				if(this.formData.users.length == 0){
					this.$message.warning('请添加收方工资单明细!')
					return
				} 
				this.btn_loading = true;
				this.$refs.payrollformaddRef.validate((valid) => {
					if (valid) {
						this.$http.post('PayrollForm/AddPayrollForm', {
							payroll: {
								...this.formData
							},
							users: this.formData.users,
						}).then(res => {
							const {
								StatusCode,
								Data,
								Message
							} = res.data || 0
							this.btn_loading = false
							if (StatusCode == 200) {
								// if (this.$refs['AnotherData'].fileList.length > 0) {
								// 	this.AnotherData.id = Data.Id
								// 	this.$refs['AnotherData'].submitUpload()
								// }
								this.$message.success('添加成功')
								this.closeFun()
								this.clearFormData()
							}else{
								this.$message.warning(Message)
							}
						}).catch(()=>{ this.btn_loading = false })
					}
				})
			},
			//清空表单数据
			clearFormData() {
				this.$refs.payrollformaddRef.resetFields()
				this.$refs.projectUserListRef.clearSelection()
				this.formData.users = []
			},
			//获取项目下的人员
			getPorjectUsers() {
				this.projectUserList = []
				let {
					UserIds
				} = this.project || ''
				let ids = UserIds.split(',')
				ids.forEach(x => {
					let user = this.$store.state.AllUsers.find(u => u.Id == x) || undefined
					if (user != undefined) this.projectUserList.push(user)
				})
			},
			//表格选中
			selectionLineChangeHandle(value, row) {
				let newvalue = [...value]
				value.forEach((x, index) => {
					const {
						Id
					} = value || 0
					let U_index = this.selectEdUserList.findIndex(u => u.Id == Id)
					if (U_index >= 0) newvalue[index] = this.selectEdUserList[U_index]
				})
				this.selectEdUserList = newvalue

				this.formData.users = this.selectEdUserList.map(x => {
					return {
						id: 0,
						delete: false,
						operatId: 0,
						operatDate: "",
						formId: 0,
						projectId: this.project.Id,
						userId: x.Id,
						jobContent: "",
						workingDays: 0,
						price: 0,
						remarks: "",
						payrollType: 0,
						formType: 0,
						jobCreateTime: '',
						jobEndTime: '',
						isupdata: true,
					}
				})

			},
			//获取用户的信息
			getUserInfo(row, type) {
				let user = this.$store.state.AllUsers.find(u => u.Id == row.userId) || undefined
				return user[type]
			},
			//表格操作
			tableHandler(row, type) {
				let index = this.formData.users.findIndex(x => x.userId == row.userId)
				if (type == "updata") {
					this.formData.users[index].isupdata = !this.formData.users[index].isupdata
				} else {
					this.formData.users.splice(index, 1)
				}
				this.$refs.projectUserListRef.clearSelection()
				this.formData.users.forEach(x => {
					let user = this.projectUserList.find(p => p.Id == x.userId)
					if (user != undefined) {
						this.$nextTick(() => {
							this.$refs.projectUserListRef.toggleRowSelection(user)
						})
					}
				})
			},
			//时间选择
			TimeChange(row) {
				const {
					jobCreateTime,
					jobEndTime,
					userId
				} = row || ''
				if (jobCreateTime != '' && jobEndTime != '') {
					row.workingDays = (dayjs(jobEndTime).diff(jobCreateTime, 'day')) + 1
					this.$http.post('PayrollForm/UserByProjectDate', {
						userId: userId,
						jobStartDate: jobCreateTime,
						jobEndDate: jobEndTime
					}).then(res => {
						const {
							Message,
							Status
						} = res.data || 0
						if (!Status) {
							this.$message.warning(Message)
							row.jobCreateTime = ''
							row.jobEndTime = ''
						}
					})
				}
			},
			timeForMat(time) {
				if (time != '') return dayjs(time).format('YYYY-MM-DD')
				else return ''
			},
			radioEvent(value){
				if(!value) {
					this.formData.settlementNumber = ''
					this.CheckSettlementResult = {
						Status: false,
						Message:'',
						StatusCode: 500,
					}
				}
			},
			//时间选择事件
			SettlementNumberEvent(value) {
				if (value == '') return
				this.$http.post('PayrollForm/CheckSettlement', {
					settlementNumber: value,
					projectId: this.project.Id
				}).then(res => {
					this.CheckSettlementResult = res.data
				})
			},
			//修改已经扎帐订单,请谨慎操作
			// IsUpSettlementHandler(){
			// 	if(!this.formData.settlement){
			// 		this.addPayrollFormHandler()				
			// 	}else{
			// 		//不存在已扎帐
			// 		if(this.CheckSettlementResult.StatusCode==200){
			// 			this.addPayrollFormHandler()
			// 		}else{
			// 			//存在已扎帐,修改原数据
			// 			this.$http.post('PayrollForm/UpSettlement', {
			// 				settlementNumber: this.formData.settlementNumber,
			// 				projectId: this.project.Id
			// 			}).then(res => {
			// 				const {
			// 					StatusCode,
			// 					Data,
			// 					Message
			// 				} = res.data || 0
			// 				if (StatusCode == 200){
			// 					this.addPayrollFormHandler()
			// 				}else{
			// 					this.$message.warning(Message)
			// 				}
			// 			})					
			// 		}					
			// 	}
			// }
		},
	}
</script>

<style scoped>
	deep .tablelabel .el-table th>.cell{
		font-size: 12px !important;
	}
</style>